package com.newear.marathon.service.impl;

import com.newear.marathon.dto.admin.maintenance.AdminLoginRequestDTO;
import com.newear.marathon.dto.admin.maintenance.AdminLoginResponseDTO;
import com.newear.marathon.dto.admin.maintenance.GenerateCaptchaResponseDTO;
import com.newear.marathon.entity.admin.AdminUser;
import com.newear.marathon.mapper.AdminUserMapper;
import com.newear.marathon.service.IAdminPublicService;
import com.newear.marathon.service.IAdminUserService;
import com.newear.marathon.utils.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author MicroBin
 * @description：TODO
 * @date 2021/3/28 10:23 下午
 */
@Service
public class AdminPublicServiceImpl implements IAdminPublicService
{
    @Autowired
    private AdminUserMapper adminUserMapper;
    @Autowired
    private IAdminUserService adminUserService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private AuthenticationManager authenticationManager;

    @Override
    public GenerateCaptchaResponseDTO doGenerateCaptcha()
    {
        GenerateCaptchaResponseDTO responseDTO = new GenerateCaptchaResponseDTO();
        TransactionStatus transactionStatus = new TransactionStatus();
        CaptchaCodeUtil captchaCodeUtil = new CaptchaCodeUtil();
        Map<String, String> map = captchaCodeUtil.getRandcode();
        //把验证码存储到redis上，有效期5分钟
        String key = RandomUtil.getRandomString(12);
        String pic = map.get(CaptchaCodeUtil.PIC);
        pic = "data:image/jpg;base64," + pic;
        responseDTO.setCaptchaCode(map.get(CaptchaCodeUtil.RANDOMSTRING));
        responseDTO.setPic(pic);
        responseDTO.setCaptchaId(key);
        responseDTO.setTransactionStatus(transactionStatus);
        stringRedisTemplate.opsForValue().set(key, map.get(CaptchaCodeUtil.RANDOMSTRING), Constant.CAPTCHA_EXPIRY_SECOND, TimeUnit.SECONDS);
        return responseDTO;
    }

    @Transactional
    @Override
    public AdminLoginResponseDTO doLoginAuth(AdminLoginRequestDTO requestDTO)
    {
        AdminLoginResponseDTO responseDTO = new AdminLoginResponseDTO();
        TransactionStatus transactionStatus = new TransactionStatus();

        //验证图形验证码
        String captcha = stringRedisTemplate.opsForValue().get(requestDTO.getCaptchaId());
        if (StringUtils.isBlank(captcha) || !captcha.equalsIgnoreCase(requestDTO.getCaptchaCode()))
        {
            throw new BaseException(ApplicationError.CAPTCHA_ERROR.getMessage(), ApplicationError.CAPTCHA_ERROR.getCode());
        }

        try
        {
            //security认证用户名、密码
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(requestDTO.getUsername(), requestDTO.getPassword());
            Authentication authenticate = authenticationManager.authenticate(authenticationToken);
            SecurityContextHolder.getContext().setAuthentication(authenticate);
        }
        catch (Exception e)
        {
            throw new BaseException(ApplicationError.USER_NAME_OR_PASSWORD_ERROR.getMessage(),
                                    ApplicationError.USER_NAME_OR_PASSWORD_ERROR.getCode());
        }
        //获取后台用户信息
        AdminUser user = adminUserService.findByUsername(requestDTO.getUsername());
        if (null == user)
        {
            throw new BaseException(ApplicationError.USER_NAME_OR_PASSWORD_ERROR.getMessage(),
                                    ApplicationError.USER_NAME_OR_PASSWORD_ERROR.getCode());
        }
        //更新登录时间、修改时间、登录次数
        AdminUser updateUser = new AdminUser();
        Date date = new Date();
        updateUser.setId(user.getId());
        updateUser.setLastLoginTime(user.getLoginTime());
        updateUser.setLoginTime(date);
        updateUser.setLoginCount(user.getLoginCount() + 1);
        //更新
        adminUserMapper.updateById(updateUser);
        //返回用户信息
        BeanUtils.copyProperties(user, responseDTO);
        responseDTO.setTransactionStatus(transactionStatus);
        return responseDTO;
    }
}
